import hashlib
from queue import Queue

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from DbObj import Base, Password
# 初始化数据库连接:
from TreeNode import TreeNode

engine = create_engine('mysql+mysqlconnector://root:yizheng@192.168.0.157:3306/test',
                       echo=True,
                       max_overflow=5,
                       pool_size=50,
                       pool_timeout=600,
                       pool_recycle=-1)
Base.metadata.create_all(engine)
DBSession = sessionmaker(bind=engine)
session = DBSession()

index = 1

data_arr = []


def create_plaintext(deep: int, length: int, strArr: list, treeNode: TreeNode):
    """
    用指定数组生成指定长度的文本
    :param deep: 当前层数
    :param len: 指定长度
    :param strArr:指定数组
    :param res_str:生成数组
    :return:
    # """
    # print(deep + 1)
    # for item in strArr:
    #     r = item + res_str
    #     dispose_plaintext(r)
    #     if deep < length - 1:
    #         create_plaintext(deep + 1, length, strArr, r)

    q = Queue()
    q.put(treeNode)
    while not q.empty():
        deep += 1
        for j in range(q.qsize()):
            node = q.get()
            for i in node.children:
                dispose_plaintext(i.allVall + i.val)
                # dispose_plaintext(i.getAllVal())
                if deep < length:
                    i.children = createNodeChildren(i.allVall + i.val, strArr)
                    q.put(i)


def dispose_plaintext(plaintext: str):
    """
    处理明文
    :param plaintext: 明文
    :return:
    """
    global data_arr
    print(plaintext)
    data_arr.append({
        'plaintext': plaintext,
        'ciphertext': computeMD5(plaintext),
    })
    if len(data_arr) > 1000:
        add()


def add():
    # pass
    session.execute(
        Password.__table__.insert(),
        data_arr
    )
    session.commit()
    data_arr.clear()


def computeMD5(message):
    m = hashlib.md5()
    m.update(message.encode(encoding='utf-8'))
    return m.hexdigest()


def create():
    # 键盘上字符的ASCII
    ascii_arr = list(range(33, 127))
    a = []
    # ascii转字符
    for i in ascii_arr:
        a.append(chr(i))
    # a = ['a', 'b', 'c']
    root = TreeNode()
    root.children = createNodeChildren(root.val, a)
    create_plaintext(0, 3, a, root)
    add()


def createNodeChildren(parentVal, arr):
    r = []
    for i in arr:
        node = TreeNode()
        node.allVall = parentVal
        node.val = i
        r.append(node)
    return r


if __name__ == '__main__':
    create()
    # print(len([1, 2, 3]))
